<?php

namespace App\Http\Controllers\Admin\Type;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class TypeController extends Controller
{
    //展示类型列表
    public function getIndex()
    {
    	$data = DB::table('type') -> get();
    	return view('admin.type.list',['title' => '类型列表','data' => $data]);
    }
    //展示类型添加页面
    public function getAdd()
    {
    	return view('admin.type.add',['title' => '类型添加']);
    }
    //类型的插入
    public function postInsert(Request $request)
    {
    	// dd($request -> all());
	    $this->validate($request, [
	        'type_name' => 'required|unique:type',
    	],[
    		'type_name.required' => '类型名不能为空',
    		'type_name.unique' => '类型名重名',
    	]);

    	$data = $request -> except('_token');
    	$res = DB::table('type') -> insert($data);
    	if($res)
    	{
    		return redirect('admin/type/index') -> with(['info' => '添加成功']);
    	}else
    	{
    		return back() -> with(['info' => '添加失败']);
    	}
    }
    //展示类型编辑页面
    public function getEdit($id)
    {
    	$data = DB::table('type') -> where('id', $id) -> first();
    	return view('admin.type.edit',['title' => '类型编辑','data' => $data]);
    }
    //实现类型编辑功能
    public function postUpdate(Request $request,$id)
    {
    	$data = $request -> except('_token');

    	$res = DB::table('type') -> where('type_name',$data['type_name']) ->first();
    	if(!$res)
    	{
    		DB::table('type') -> where('id', $id) ->update($data);
    		return redirect('admin/type/index') ->with(['info' =>'编辑成功']);
    	}else
    	{
    		return back() -> with(['info' => '类型名重复']);
    	}
    }
    public function getDelete($id)
    {
        //删除类型之前 先把属性删除
        $res = DB::table('attribute') -> where('type_id', $id) -> get();
        if($res)
        {
            //删除属性
            $attribute_res = DB::table('attribute')-> where('type_id', $id) -> delete();
            if($attribute_res)
            {
                $type_res = DB::table('type') -> where('id', $id) -> delete();
                if($type_res)
                {
                    return redirect('admin/type/index') -> with(['info' => '删除成功']);
                }else
                {
                    return back() -> with(['info' => '删除失败']);
                }
            }else
            {
                 return back() -> with(['info' => '删除失败']);
            }
        }else
        {
            //删除类型
            $type_res = DB::table('type') -> where('id', $id) -> delete();
            if($type_res)
            {
                return redirect('admin/type/index') -> with(['info' => '删除成功']);
            } else
            {
                return back() -> with(['info' => '删除失败']);
            }
        }
    }
}
